package com.laivi.basic.model.file.writer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.laivi.basic.module.log.Log;
import com.laivi.basic.module.log.Logs;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-10
 * description:
 */
public class XlsxWriter implements IExcelWriter {
	private final static Log log=Logs.getLog(XlsxWriter.class);
	
	private Workbook book;
	private Sheet sheet;
	
	private File file;
	
	public XlsxWriter(String path){
		this(new File(path));
	}
	
	public XlsxWriter(File file){
		this.file=file;
		if(file.getName().endsWith(".xlsx")){
			book=new XSSFWorkbook();
		}else{
			book=new HSSFWorkbook();
		}
	}

	@Override
	public void setSheet(int index) {
		sheet=book.getSheetAt(index);
		if(sheet==null){
			sheet=book.createSheet("sheet"+index);
		}
	}

	@Override
	public void writeCell(int row, int col, String content) {
		sheet.createRow(row).createCell(col).setCellValue(content);
	}

	@Override
	public void writeCell(int row, char col, String content) {
		int colNum=Character.toUpperCase(col)-65;
		writeCell(row,colNum,content);
	}
	
	@Override
	public void close() {
		try {
			OutputStream stream = new FileOutputStream(file);
			if(!file.exists()) file.createNewFile();
			
			book.write(stream);
			stream.close();
		} catch (FileNotFoundException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}  
	}

}
